

import 'dart:convert';
import 'dart:ui';

import 'package:bot_toast/bot_toast.dart';
import 'package:dolqun_movies/Entities/MovieDetailsResult.dart';
import 'package:dolqun_movies/Interface/Network.dart';
import 'package:dolqun_movies/StateManagement/ModelProvider.dart';
import 'package:dolqun_movies/UI/Pages/Models/ColorThemeModel.dart';
import 'package:dolqun_movies/UI/Pages/Models/MainModel.dart';
import 'package:dolqun_movies/UI/Pages/Models/WechatApiModel.dart';
import 'package:dolqun_movies/UI/Pages/ProfilePage/BuyVipPage.dart';
import 'package:dolqun_movies/UI/Widgets/Dialogs.dart';
import 'package:dolqun_movies/UI/Widgets/DolqunAppBar.dart';
import 'package:dolqun_movies/UI/Widgets/EnsureHasSignin.dart';
import 'package:dolqun_movies/UI/Widgets/MyAnimatedRoute.dart';
import 'package:dolqun_movies/UI/Widgets/VideoPlayer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:screen/screen.dart';
import 'package:video_player/video_player.dart';

class PlayerPage extends StatefulWidget {
  MovieDetails details;
  PlayerPage({this.details}){}

  @override
  State<StatefulWidget> createState() => _PlayerPageState();
}

class _PlayerPageState extends State<PlayerPage> {
  int _selectedSectionId;

  bool _canBePlay = false;

  @override
  void initState() {
    Screen.keepOn(true);
    super.initState();
  }
  @override
  void dispose() {
    Screen.keepOn(false);
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    var theme = ModelContainer.of<ColorThemeModel>(context).model;
    Widget player = null;
    {
      if (_canBePlay) {
        var section = this.widget.details.items.firstWhere((element) => element.id == this._selectedSectionId);
        player = CustomVideoPlayer(
          id: this.widget.details.id.toString(),
          onError: (error){
            print(error);
          },
          videoName: "${this.widget.details.name}:${section.name}",
          videoUrl: String.fromCharCodes(Base64Decoder().convert(section.items.first.url)),
        );
      } else
      player = SizedBox(
        height: 100.0,
        child: Center(
          child: Text("Please select below items to play this video"),
        ),
      );
    }
    var size = MediaQuery.of(context).size;
    var isLandscape = false;//size.width > size.height;
    return Scaffold(
      appBar: isLandscape ? null : DolqunAppBar(),
      body: isLandscape ? player : Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          player,
          Divider(),
          Wrap(
            children: (widget.details?.items ?? []).map((item){
              var selected = item.id == _selectedSectionId;
              return InkWell(
                child: AnimatedContainer(
                  duration: Duration(milliseconds: 300),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.0),
                    color: selected ? theme.textColor : Colors.white.withOpacity(0.04),
                  ),
                  padding: EdgeInsets.all(5.0),
                  margin: EdgeInsets.all(3.0),
                  child: Directionality(
                    textDirection: TextDirection.ltr,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        if (!item.buy) Text("${item.price}¥", style: TextStyle(color: Colors.red, fontSize: 10.0),),
                        Text(item.name),
//                        Icon(Icons.list, color: Colors.white30,),
                      ],
                    ),
                  ),
                ),
                onTap: (){
                  this._selectedSectionId = item.id;
                  _play().then((value){
                    setState(() {
                      if (value) {
                        setState(() {
                          this._canBePlay = false;
                        });
                        SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
                          setState(() {
                            this._canBePlay = value;
                          });
                        });
                      } else
                        this._canBePlay = value;
                    });
                  });
                },
              );
            }).toList(),
          )
        ],
      ),
    );
  }

  Future<bool> _play() async {
    var wechatApi = ModelContainer.of<WechatApiModel>(context).model;
    var model = ModelContainer.of<MainModel>(context).model;

    var getSection = () => this.widget.details.items.where((element) => element.id == this._selectedSectionId).first;
    var section = getSection();
    var navigateAction = (){
      //Navigator.of(context).push(MyAnimatedRoute(builder: (context) => PlayerPage(details: details, videoName: details.data.name,),));
      return true;
    };
    if (!section.buy) {
      EnsureHasSignIn.runWhenSignIn(context, () async {
        Dialogs.runWithDialogsWhenErrorOccurres(context, ()async {
          Future<void> paymentAction() async {
            if (!section.buy) {
              PaymentFor _paymentForWhat = PaymentFor.SingleMediaSegment;
              var id = section.id;
//                                          var result = await showDialog(context: context, child: CupertinoAlertDialog(
//                                            title: Text("ھەق تاپشۇرۇش"),
//                                            content: Directionality(
//                                              textDirection: TextDirection.rtl,
//                                              child: Material(
//                                                color: Colors.transparent,
//                                                child: Column(
//                                                  children: <Widget>[
//                                                    ListTile(
//                                                      leading: Text(section.price.toString()),
//                                                      title: Text("مۇشۇ قىسىمنىلا سېتىۋالاي"),
//                                                      subtitle: Text("باھاسى ئەرزان، قولاي، چاققان"),
//                                                      onTap: (){
//                                                        Navigator.of(context).pop(true);
//                                                      },
//                                                    ),
//                                                    Divider(),
//                                                    if (!this.details.data.buy) ...[
//                                                      ListTile(
//                                                        leading: Text(details.data.price.toString()),
//                                                        title: Text("ھەممە قىسىمنى سېتىۋالاي"),
//                                                        subtitle: Text("كۆپ قىسىم بولغاندا ئەرزان، چەكلىمىسىز"),
//                                                        onTap: (){
//                                                          _paymentForWhat = PaymentFor.WholeMediaSegment;
//                                                          id = this.details.data.id;
//                                                          Navigator.of(context).pop(true);
//                                                        },
//                                                      ),
//                                                      Divider()
//                                                    ],
//                                                    ListTile(
//                                                      title: Text("VIP بېتى"),
//                                                      subtitle: Text("تىخىمۇ كۆپ ئىتىبارلار"),
//                                                      onTap: ()async {
//                                                        await Navigator.of(context).push(MaterialPageRoute(builder: (context) => BuyVipPage(),));
//                                                      },
//                                                    )
//                                                  ],
//                                                ),
//                                              ),
//                                            ),
//                                            actions: <Widget>[
//                                              CupertinoButton(
//                                                child: Text("بولدىلا"),
//                                                onPressed: (){
//                                                  Navigator.of(context).pop(false);
//                                                },
//                                              )
//                                            ],
//                                          ));
              var result = await showDialog(context: context, child: Center(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(20.0),
                  child: BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 30.0, sigmaY: 30.0),
                    child: Container(
                      width: 320.0,
                      color: Color(0xe8ecff).withOpacity(0.04),
                      child: Directionality(
                        textDirection: TextDirection.rtl,
                        child: Material(
                          color: Colors.transparent,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              Container(
                                color: Colors.white.withOpacity(0.04),
                                width: double.infinity,
                                height: 60.0,
                                alignment: Alignment.center,
                                child: Text("ھەق تاپشۇرۇش", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),),
                              ),
                              SizedBox(height: 10.0,),
                              _ListTile(
                                leading: CircleAvatar(
                                  backgroundColor: Colors.white.withOpacity(0.04),
                                  radius: 30.0,
                                  child: Text(section.price.toString()),
                                ),
                                title: Text("مۇشۇ قىسىمنىلا سېتىۋالاي"),
                                subtitle: Text("باھاسى ئەرزان، قولاي، چاققان"),
                                onTap: (){
                                  Navigator.of(context).pop(true);
                                },
                                trailing: Icon(Icons.arrow_forward_ios, color: Colors.blue,),
                              ),
                              Divider(),
                              if (!this.widget.details.buy) ...[
                                _ListTile(
                                  leading: CircleAvatar(
                                    backgroundColor: Colors.white.withOpacity(0.04),
                                    radius: 30.0,
                                    child: Text("${this.widget.details.price}"),
                                  ),
                                  title: Text("ھەممە قىسىمنى سېتىۋالاي"),
                                  subtitle: Text("كۆپ قىسىم بولغاندا ئەرزان، چەكلىمىسىز"),
                                  onTap: (){
                                    _paymentForWhat = PaymentFor.WholeMediaSegment;
                                    id = this.widget.details.id;
                                    Navigator.of(context).pop(true);
                                  },
                                  trailing: Icon(Icons.arrow_forward_ios, color: Colors.blue,),
                                ),
                                Divider()
                              ],
                              _ListTile(
                                leading: CircleAvatar(
                                  backgroundColor: Colors.white.withOpacity(0.04),
                                  radius: 30.0,
                                  child: Text("VIP"),
                                ),
                                title: Text("VIP بېتى"),
                                subtitle: Text("تىخىمۇ كۆپ ئىتىبارلار"),
                                onTap: ()async {
                                  await Navigator.of(context).push(MyAnimatedRoute(builder: (context) => BuyVipPage(),));
                                },
                                trailing: Icon(Icons.arrow_forward_ios, color: Colors.blue,),
                              ),
                              SizedBox(height: 10.0,),
                              Container(
                                  color: Colors.white.withOpacity(0.04),
                                  width: double.infinity,
                                  height: 60.0,
                                  alignment: Alignment.center,
                                  child: FlatButton(
                                    child: Text("بولدىلا", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue)),
                                    onPressed: (){
                                      Navigator.of(context).pop(false);
                                    },
                                  )
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ));

              if ((result ?? false) == false) return;
              BotToast.showLoading();
              var paymentRequest = (await model.api.requestPayment(_paymentForWhat, id, wechatApi.token)).data;
              wechatApi.payment(paymentRequest).then((value) async {
                this.widget.details = null;
                if (value == false) {
                  await model.api.cancelPaymentOrder(wechatApi.token, paymentRequest.outTradeNo);
                  print("payment order cancelled.");
                  BotToast.showText(text: "payment order cancelled.");
                }
                setState(() {});
              });
            }
          }
          {
            BotToast.showLoading();
            this.widget.details = (await model.api.getMovieDetails(wechatApi.token, this.widget.details.id)).data;
            BotToast.closeAllLoading();
            setState(() {});
            section = getSection();
            if (!section.buy) await paymentAction();
            else navigateAction();
          }
        }, onError: () => BotToast.closeAllLoading(), onCompleted: () => BotToast.closeAllLoading());
      });
      return section.buy;
    }
    return navigateAction();
  }

  Widget _ListTile({Widget title, Widget subtitle, Widget leading, Widget trailing, void onTap()}){
    return InkWell(
      onTap: onTap,
      child: Row(
        children: [
          SizedBox(width: 10.0,),
          leading,
          SizedBox(width: 10.0,),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              AnimatedDefaultTextStyle(
                style: Theme.of(context).textTheme.bodyText1.copyWith(fontWeight: FontWeight.bold, fontSize: 16.0, color: Colors.white),
                duration: Duration(seconds: 1),
                child: title,
              ),
              AnimatedDefaultTextStyle(
                style: Theme.of(context).textTheme.bodyText1.copyWith(fontWeight: FontWeight.bold, fontSize: 12.0, color: Colors.white70),
                duration: Duration(seconds: 1),
                child: subtitle,
              ),
            ],
          ),
          Spacer(),
          trailing,
          SizedBox(width: 10.0,),
        ],
      ),
    );
  }
}
